package com.kettle.controller;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.repository.filerep.KettleFileRepository;
import org.pentaho.di.repository.filerep.KettleFileRepositoryMeta;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kettle.controllerapis.KettleControllerApi;
import com.kettle.model.datalog.Datalog;
import com.kettle.model.kettle.Basepost;
import com.kettle.model.kettle.Kettlemap;
import com.kettle.model.kettle.Kettlework;
import com.kettle.model.quartz.ReturnResult;
import com.kettle.model.rowpage.PageResult;
import com.kettle.service.datalog.DatalogService;
import com.kettle.service.kettle.KettleService;
import com.kettle.service.kettle.KettlesendService;
import com.kettle.service.quart.QuartzService;

/**
 * kettle 控制层
 * @author king
 *
 */
@Controller
@RequestMapping("/")
public class KettleController implements KettleControllerApi{
	
	@Resource
	private KettleService kettleService;

	@Resource
	private KettlesendService kettlesendService;

	@Resource
    private QuartzService quartzService;

	@Resource
	private DatalogService datalogService;

	@Value("${kettlepath.lnurlpath}")
	private String lnurlpath;

	@Value("${kettlepath.lnmfilepath}")
	private String lnmfilepath;
	
	@Override
	@RequestMapping(value="/index",method = RequestMethod.GET)
    public String index(Model model){
        return "kmindex";
    }
	
	@Override
	@RequestMapping(value="v1/searchkettlelist",method = RequestMethod.POST)
    public @ResponseBody PageResult kettlelist(Model model,String title,Integer page, Integer rows){
		QueryWrapper<Kettlework> entityWrapper = new QueryWrapper<>();
        //通过标题查询
       if(!"".equals(title) && title!=null){
            entityWrapper.like("title",title.trim());
        }
        PageResult result = new PageResult(); 
		PageInfo<Kettlework> pageInfo; 
	    try{
	    	PageHelper.startPage(page,rows,"createtime desc");
	    	List<Kettlework> list= kettleService.list(entityWrapper);
	        pageInfo = new PageInfo<Kettlework>(list);
	        result.setTotal(pageInfo.getTotal());
	        result.setRows(list);
	    } finally {
	        PageHelper.clearPage();
	    }
	    return result;
    }
	
	@Override
	@RequestMapping(value="v1/savekettle",method = RequestMethod.POST)
	public @ResponseBody ReturnResult kettlesave(Model model,Kettlework kettlework){
		ReturnResult result=new ReturnResult();
		Map<String,Object> kmsmap=new HashMap<String,Object>();	
		kmsmap.put("jobname", kettlework.getJobname());
		kmsmap.put("jobgroupname", kettlework.getJobgroupname());
		kmsmap.put("id", null);
		boolean khave=kettleService.isshowcount(kmsmap);
		if(khave){
			String uuid = UUID.randomUUID().toString();
			uuid = uuid.replace("-", "");
			kettlework.setId(uuid);
			Timestamp createtime = new Timestamp(System.currentTimeMillis());
			kettlework.setCreatetime(createtime);
			boolean issave=kettleService.save(kettlework);
			result.setCode("500");
			result.setSuccess(false);
			if(issave){
				result.setCode("200");
				result.setSuccess(true);
				result.setMsg("保存成功");
			}else{
				result.setMsg("保存失败");
			}
		}else{
			result.setCode("500");
			result.setSuccess(false);
			result.setMsg("已存在工作名称和工作组名");	
		}
		return result;
	}
	@Override
	@RequestMapping(value="v1/updatekettle",method = RequestMethod.POST)
	public @ResponseBody ReturnResult kettleupdate(Kettlework kettlework){
		ReturnResult result=new ReturnResult();
		Map<String,Object> kmsmap=new HashMap<String,Object>();	
		kmsmap.put("jobname", kettlework.getJobname());
		kmsmap.put("jobgroupname", kettlework.getJobgroupname());
		kmsmap.put("id", kettlework.getId());
		boolean khave=kettleService.isshowcount(kmsmap);
		if(khave){
			boolean issave=kettleService.updateById(kettlework);
			result.setCode("500");
			result.setSuccess(false);
			if(issave){
				result.setCode("200");
				result.setSuccess(true);
				result.setMsg("修改成功");
			}else{
				result.setMsg("修改失败");
			}
		}else{
			result.setCode("500");
			result.setSuccess(false);
			result.setMsg("已存在工作名称和工作组名");	
		}
		return result;
	}
	@Override
	@RequestMapping(value="v1/deletekettle",method = RequestMethod.POST)
	public @ResponseBody ReturnResult kettledelete(Model model,String id){
		ReturnResult result=new ReturnResult();
		boolean issave=kettleService.removeById(id);
		result.setCode("500");
		result.setSuccess(false);
		if(issave){
			result.setCode("200");
			result.setSuccess(true);
			result.setMsg("删除成功");
		}else{
			result.setMsg("删除失败");
		}
		return result;
	}
	@Override
	@RequestMapping(value="v1/savefile",method = RequestMethod.POST)
    public @ResponseBody Map<String,Object> ksaveorup(HttpServletRequest request,Kettlework kettlework
    		,@RequestParam(value="contractFile") MultipartFile[] multipartfile){
		String kfile= request.getSession().getServletContext().getRealPath("/");
		kettleService.savekettlefile(multipartfile,kfile);
		return null;
	}	
	
	@Override
	@RequestMapping(value="v1/sfzxz",method =RequestMethod.POST)
	public @ResponseBody Kettlemap sfzxz(HttpServletRequest request,
			   @RequestBody(required=false) String requestBody){
		Kettlemap knap=new Kettlemap();
		Map<String,Object> pastmap=new HashMap<String,Object>();
		Basepost rdtop=JSON.parseObject(requestBody,Basepost.class);
		String jobname=rdtop.getJobname();
		String jobgroupname=rdtop.getJobgroupname();
		pastmap.put("jobname", jobname);
		pastmap.put("jobgroupname", jobgroupname);
		List<Kettlework> mapid=kettleService.listByMap(pastmap);
		String kid=mapid.size() > 0 ? mapid.get(0).getId() : "";
		//判断是否存在正在执行记录
		if(!"".equals(kid) && kid!=null){
			String clzt=mapid.get(0).getCzzt();
		    if("3".equals(clzt)){
		    	knap.setSuccess(false);
		    	knap.setZxbzlog("工作任务正在执行中，请稍后重试!");
		    	knap.setMsgtype("2");
		    	knap.setLogs("工作任务正在执行中，请稍后重试!");
		    	return knap;
			}
		}else{
			knap.setSuccess(false);
	    	knap.setZxbzlog("未找到该工作任务，请核查工作任务是否存在!");
	    	knap.setMsgtype("3");
	    	knap.setLogs("未找到该工作任务，请核查工作任务是否存在!");
	    	return knap;
		}
		knap.setSuccess(true);
    	knap.setZxbzlog("该工作任务没有在执行");
    	knap.setMsgtype("1");
    	knap.setLogs("该工作任务没有在执行!");
		

		return knap;
	}	
	
	@Override
	@RequestMapping(value="v1/executejob",method =RequestMethod.POST)
	public @ResponseBody Kettlemap kettlesendJob(HttpServletRequest request,
		   @RequestBody(required=false) String requestBody){
		Map<String,Object> pastmap=new HashMap<String,Object>();
		Basepost rdtop=JSON.parseObject(requestBody,Basepost.class);
		String jobname=rdtop.getJobname();
		String jobgroupname=rdtop.getJobgroupname();
		Map<String, Object>  param = 	rdtop.getKsendmap();	
		pastmap.put("jobname", jobname);
		pastmap.put("jobgroupname", jobgroupname);
		List<Kettlework> mapid=kettleService.listByMap(pastmap);
		String kid=mapid.size() > 0 ? mapid.get(0).getId() : "";
		Kettlemap knap=new Kettlemap();
		knap.setSuccess(true);
		//判断是否存在正在执行记录
		String filepath="";
		if(!"".equals(kid) && kid!=null){
			String clzt=mapid.get(0).getCzzt();
			filepath=mapid.get(0).getFilepath();
		    if("3".equals(clzt)){
		    	knap.setSuccess(false);
		    	knap.setZxbzlog("工作任务正在执行中，请稍后重试!");
		    	knap.setMsgtype("2");
		    	knap.setLogs("工作任务正在执行中，请稍后重试!");
		    	return knap;
			}
		}else{
			knap.setSuccess(false);
	    	knap.setZxbzlog("未找到该工作任务，请核查工作任务是否存在!");
	    	knap.setMsgtype("2");
	    	knap.setLogs("未找到该工作任务，请核查工作任务是否存在!");
	    	return knap;
		}
		Datalog kmap=new Datalog();
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		kmap.setId(uuid);
		kmap.setJobname(jobname);
		kmap.setJobgroupname(jobgroupname);
		kmap.setLxdm("1");
		kmap.setZxlb("2");
		Timestamp start = new Timestamp(System.currentTimeMillis());
		Kettlework kwork=new Kettlework();
		kwork.setId(kid);
		kwork.setCzzt("3");
		kwork.updateById();//初始更新为3,正在执行
		try {
			EnvUtil.environmentInit();
			//String kfile=SysUtils.pcurlpath+SysUtils.pcmfilepath;
			String kfile=lnurlpath+lnmfilepath;
			System.setProperty("java.naming.factory.initial","weblogic.jndi.WLInitialContextFactory");
			if(!KettleEnvironment.isInitialized()){
				// Kettle初始化需要修改相应的配置路径  
				System.setProperty("user.dir",kfile);
				System.setProperty("KETTLE_HOME",kfile);
				KettleEnvironment.init(true);
			}
			// 资源库元对象
			KettleFileRepositoryMeta repinfo = new KettleFileRepositoryMeta("kettle","kettle","数据采集",kfile);
			// 文件形式的资源库
			KettleFileRepository repository = new KettleFileRepository();
			repository.init(repinfo);
			filepath="";//默认为空时不影响之前, 后期升级需要开启
			param.put("filepath","".equals(filepath)?"/":"/"+filepath);
			knap=kettlesendService.execJob(repository,jobname,filepath,param, null);//后面两个参数分别为
			Timestamp end = new Timestamp(new Date().getTime()); 
			String czzt=knap.isSuccess()?"1":"2";
			kmap.setKssj(start);
			kmap.setJssj(end);
			kmap.setCzzt(czzt);
			kmap.setZxbz(knap.getZxbzlog());
			kmap.setLogs(knap.getLogs());
		} catch (KettleException e) {
			knap.setSuccess(false);
			knap.setZxbzlog("出现异常");
			knap.setLogs("出现异常:"+e.getMessage());
			e.printStackTrace();
			Timestamp end = new Timestamp(System.currentTimeMillis());
			kmap.setKssj(start);
			kmap.setJssj(end);
			kmap.setCzzt("2");
			kmap.setZxbz("出现异常");
			kmap.setLogs(e.getMessage()==null?"出现异常":e.getMessage());
		}finally{
			datalogService.save(kmap);
			kwork.setKssj(kmap.getKssj());
			kwork.setJssj(kmap.getJssj());
			kwork.setCzzt(kmap.getCzzt());
			kettleService.updateById(kwork);
		}
		return knap;
	}
	
	@Override
	@RequestMapping(value="v1/executetran",method = RequestMethod.POST)
	public @ResponseBody Kettlemap kettlesendTran(HttpServletRequest request,
		   @RequestBody(required=false) String requestBody){
		Kettlemap knap=new Kettlemap();
		Datalog kmap=new Datalog();
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		kmap.setId(uuid);
		Basepost rdtop=JSON.parseObject(requestBody,Basepost.class);
		String jobname=rdtop.getJobname();
		String jobgroupname=rdtop.getJobgroupname();
		kmap.setJobname(jobname);
		kmap.setJobgroupname(jobgroupname);
		kmap.setLxdm("2");
		kmap.setZxlb("2");
		Timestamp start = new Timestamp(System.currentTimeMillis());
		try {
			EnvUtil.environmentInit();
			//String kfile=SysUtils.pcurlpath+SysUtils.pcmfilepath;
			String kfile=lnurlpath+lnmfilepath;
			if(!KettleEnvironment.isInitialized()){
				// Kettle初始化需要修改相应的配置路径   
				System.setProperty("java.naming.factory.initial","weblogic.jndi.WLInitialContextFactory");
				System.setProperty("user.dir",kfile);
				System.setProperty("KETTLE_HOME",kfile);
				KettleEnvironment.init(true);
			}
			// 资源库元对象
			KettleFileRepositoryMeta repinfo = new KettleFileRepositoryMeta("kettle","kettle","数据采集",kfile);
			// 文件形式的资源库
			KettleFileRepository repository = new KettleFileRepository();
			repository.init(repinfo);
			knap=kettlesendService.execTran(repository,jobname, null, null);//后面两个参数分别为
			Timestamp end = new Timestamp(new Date().getTime()); 
			String czzt=knap.isSuccess()?"1":"2";
			kmap.setKssj(start);
			kmap.setJssj(end);
			kmap.setCzzt(czzt);
			kmap.setZxbz(knap.getZxbzlog());
			kmap.setLogs(knap.getLogs());
		}catch (KettleException e) {
			knap.setSuccess(false);
			knap.setZxbzlog("出现异常");
			knap.setLogs("出现异常:"+e.getMessage());
			e.printStackTrace();
			Timestamp end = new Timestamp(new Date().getTime()); 
			kmap.setKssj(start);
			kmap.setJssj(end);
			kmap.setCzzt("2");
			kmap.setZxbz("出现异常");
			kmap.setLogs(e.getMessage()==null?"出现异常":e.getMessage());
		}finally{
			datalogService.save(kmap);
		}
		return knap;
	}
	
	@Override
	@RequestMapping(value="v1/executequartzjob",method =RequestMethod.POST)
	public @ResponseBody Kettlemap kettlequeatzjob(HttpServletRequest request,
		   @RequestBody(required=false) String requestBody){
		Kettlemap knap=new Kettlemap();
		Map<String,Object> pastmap=new HashMap<String,Object>();
		Basepost rdtop=JSON.parseObject(requestBody,Basepost.class);
		String jobname=rdtop.getJobname();
		String jobgroupname=rdtop.getJobgroupname();
		Map<String, Object>  param = 	rdtop.getKsendmap();	
		pastmap.put("jobname", jobname);
		pastmap.put("jobgroupname", jobgroupname);
		List<Kettlework> mapid=kettleService.listByMap(pastmap);
		String triggerName="";
		String triggerGroupName="";
		String classstr="";
		String kid=mapid.size() > 0 ? mapid.get(0).getId() : "";
		if(!"".equals(kid) && kid!=null){
			String clzt=mapid.get(0).getCzzt();
			triggerName="tig"+kid;
			triggerGroupName="tigergroup";
			classstr="com.kettle.job.QuyartzJob";
		    if("3".equals(clzt)){
		    	knap.setSuccess(false);
		    	knap.setZxbzlog("工作任务正在执行中，请稍后重试!");
		    	knap.setMsgtype("2");
		    	knap.setLogs("工作任务正在执行中，请稍后重试!");
		    	return knap;
			}
		}else{
			knap.setSuccess(false);
	    	knap.setZxbzlog("未找到该工作任务，请核查工作任务是否存在!");
	    	knap.setMsgtype("2");
	    	knap.setLogs("未找到该工作任务，请核查工作任务是否存在!");
	    	return knap;
		}
		try {
			quartzService.addOnceJob(jobname, jobgroupname, triggerName, triggerGroupName,Class.forName(classstr), param);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			knap.setSuccess(false);
	    	knap.setZxbzlog("出现异常!");
	    	knap.setMsgtype("2");
	    	knap.setLogs("出现异常:"+e.getMessage());
	    	return knap;
		}
		return null;
	}
	
}
